(function(){
	YozmCup = function(){
		this.sexCode = "M"; 
		
		this.gameLevel = 1;
		this.gameCnt = 0;

		this.isIng = false;
		this.playerCnt = 8;
		this.memberList = [];
		this.playerList = [];
		this.playerHistory = [];
		
		this.loadInfo = $("loadInfo");
		this.stage = $("stage");
		this.result = $("result");
		this.startBtn = $("startCup");
		this.selector = $("selector");
		this.round = $("gameRound");
		this.memberTemplate = new daum.Template(
			"<img id=\"\#{cupId}\" class=\"member_image\" src=\"\#{profile_big_img_url}\" />"
			+ "<div class=\"member_desc\">"
			+ "<a href=\"http://yozm.daum.net/\#{url_name}\" target =\"_blank\">\#{nickname}</a>"
			+ "<p>\#{user_info.introduce}</p>"
			+ "</div>"
		);
		this.resultTemplate = new daum.Template(
			"<p class=\"winner_title\">WINNER</p>"
			+ "<a href=\"http://yozm.daum.net/\#{url_name}\" target =\"_blank\"><img id=\"\#{cupId}\" class=\"winner_image\" src=\"\#{profile_big_img_url}\" /></a>"
			+ "<div class=\"winner_desc\">"
			+ "<a href=\"http://yozm.daum.net/\#{url_name}\" target =\"_blank\">\#{nickname}</a>"
			+ "<p>\#{user_info.introduce}</p>"
			+ "</div>"
		);
		this.left = -1;
		this.right = -1;
		
		daum.Event.addEvent(this.startBtn, "click", this.start.bind(this));
		daum.Event.addEvent(this.stage, "click", this.choice.bind(this));
	}
	YozmCup.prototype = {
		start: function(){
			if(this.isIng){
				alert("게임 생성중입니다");
				return;
			}
			this.isIng = true;
			
			var type = "";
			$$("[name=kind]").each(function(){
				var rd = arguments[0];
				if(rd.checked){
					type = rd.value;
				}
			});
			daum.Element.hide(this.selector);
			daum.Element.addClassName(this.startBtn, "making");
			if(type==="winner"){
				this.addLoadinfo("역대 요즘컵 우승자들을 로드중입니다...");
				new daum.Ajax({onsuccess:function(r){
					var result = (r.responseText!="")?daum.Ajax.jsonToObject(r.responseText):null;
					if(result != null && result.status === 200){
						this.memberList = this.memberList.concat(result.user_list);
						this.makeStage();
					}else{
						this.loadFail();
					}
				}.bind(this)}).request("/StartCup?cmd=winner");
			}else{
				this.addLoadinfo("내 친구를 로드중입니다...");
				new daum.Ajax({onsuccess:function(r){
					var result = (r.responseText!="")?daum.Ajax.jsonToObject(r.responseText):null;
					if(result != null && result.status === 200){
						this.memberList = this.memberList.concat(result.user_list);
						if(this.memberList.length < this.playerCnt){
							this.getFollower();
						}else{
							this.makeStage();
						}
					}else{
						this.loadFail();
					}
				}.bind(this)}).request("/StartCup?cmd=following");
			}
		},
		getFollower: function(callback){
			this.addLoadinfo("나를 좋아하는 친구를 로드중입니다...");
			new daum.Ajax({onsuccess:function(r){
				var result = (r.responseText!="")?daum.Ajax.jsonToObject(r.responseText):null;
				if(result != null && result.status === 200){
					this.memberList = this.memberList.concat(result.user_list);
					if(this.memberList.length < this.playerCnt){
						this.getRecommender();
					}else{
						this.makeStage();
					}
				}else{
					this.loadFail();
				}
			}.bind(this)}).request("/StartCup?cmd=followers");  
		},
		getRecommender: function(){
			this.addLoadinfo("추천친구를 로드중입니다...");
			new daum.Ajax({onsuccess:function(r){
				var result = (r.responseText!="")?daum.Ajax.jsonToObject(r.responseText):null;
				if(result != null && result.status === 200){
					this.memberList = this.memberList.concat(result.user_list);
					if(this.memberList.length < this.playerCnt){
						this.loadFail();
					}else{
						this.makeStage();
					}
				}else{
					this.loadFail();
				}
			}.bind(this)}).request("/StartCup?cmd=recommend_friends");
		},
		makeStage: function(isWinner){
			this.addLoadinfo("참가자풀이 완성되었습니다. 맘에 드는분을 선택하세요!!");
			this.finishLoad();
			daum.Element.show(this.stage);
			this.makePlayer(isWinner);
			this.playerHistory = this.playerList.copy();
			this.startCup();
		},
		makePlayer: function(isWinner){
			if(this.sexCode!="N"){
				this.checkSex();
			}
			if(!isWinner){
				if(this.playerList.length < this.playerCnt){
					this.checkBothFollow();		
				}
			}
			if(this.playerList.length < this.playerCnt){
				this.randomAdd();
			}
			if(this.playerList.length > this.playerCnt){
				this.randomRemove();
			}
			this.shake();
		},
		checkSex: function(){
			var wantCode = "F";
			var tempMember = [];
			if(this.sexCode==="F"){
				wantCode = "M";
			}
			for(var i=0, len=this.memberList.length;i<len;i++){
				var member = this.memberList[i];
				if(member.sex_code===wantCode){
					this.playerList.push(member);
				}else{
					tempMember.push(member);
				}
			}
			this.memberList = tempMember;
		},
		checkBothFollow: function(){
			var tempMember = [];
			for(var i=0, len=this.memberList.length;i<len;i++){
				var member = this.memberList[i];
				if(member.is_both_follow){
					this.playerList.push(member);
				}else{
					tempMember.push(member);
				}
			}
			this.memberList = tempMember;
		},
		randomAdd: function(){
			while(this.playerList.length < this.playerCnt){
				var memberCnt = this.memberList.length;
				var cnt = this.getRandom(memberCnt);
				this.playerList.push(this.memberList.splice(cnt,1)[0]);
			}
		},
		randomRemove: function(){
			while(this.playerList.length > this.playerCnt){
				var memberCnt = this.playerList.length;
				var cnt = this.getRandom(memberCnt);
				this.playerList.splice(cnt, 1);
			}
		},
		shake: function(){
			var cnt = this.playerCnt;
			while(cnt>0){
				cnt--;
				var dest = this.getRandom(this.playerCnt);
				this.playerList.splice(dest, 0, this.playerList.splice(cnt, 1)[0]);
			}
		},
		getRandom: function(num){
			return parseInt(Math.random()*num);
		},
		checkRound: function(){
			this.round.innerHTML = (this.playerCnt/Math.pow(2, this.gameLevel-1)) + "강";
		},
		startCup: function(){
			this.checkRound();
			this.setRival();
		},
		setRival: function(){
			var lInd = this.gameCnt; 
			var rInd = this.gameCnt + 1;
			var firstMember = this.playerList[lInd];
			var secondMember = this.playerList[rInd];
			firstMember["cupId"] = "left";
			secondMember["cupId"] = "right";
			$("fisrtMember").innerHTML = this.memberTemplate.evaluate(firstMember);
			$("secondMember").innerHTML = this.memberTemplate.evaluate(secondMember); 
		},
		choice: function(ev){
			var el = daum.Event.getElement(ev);
			if(el.tagName.toLowerCase() == "img"){
				var position = el.id;
				daum.Event.stopEvent(ev);

				this.gameCnt++;
				if(position=="left"){
					this.playerList.splice(this.gameCnt, 1);
				}else{
					this.playerList.splice(this.gameCnt-1, 1);
				}
				if(this.playerList.length==1){
					this.finish();
					return;
				}
				var chkCnt = (this.gameCnt)*this.gameLevel;
				if(((this.playerCnt/chkCnt)==2) && ((this.playerCnt%chkCnt)==0)){
					this.gameLevel++;
					this.gameCnt = 0;
					this.checkRound();
				}
				this.setRival();
			}
		},
		finish: function(){
			daum.Element.hide(this.stage);
			var player = this.playerList[0];
			this.saveWinner(player);
			this.result.innerHTML = this.resultTemplate.evaluate(player);
			daum.Element.show(this.result);
			daum.Element.show($("write"));
			daum.Event.addEvent($("write"), "click", this.write.bind(this));
		},
		saveWinner: function(winner){
			var param = "url_name=" + (winner.url_name || "") +
				"&nickname=" + (winner.nickname || "") +
				"&sex_code=" + (winner.sex_code || "") +
				"&profile_big_img_url=" + (winner.profile_big_img_url || "") +
				"&introduce=" + (winner.user_info.introduce || "");
			var option = {
				paramString: param,
				method: "post"
			}
			new daum.Ajax().request("/SaveWinner", option);
		},
		write: function(){
			var winner = this.playerList[0];
			var form = $("writeForm");
			
			var message = $("message");
			var url = "\#\#_LINK|"+ winner.nickname +"|http://yozm.daum.net/"+winner.url_name+"_\#\#";
			var img_url = $("img_url");
			var str = "요즘컵 승자 " + url + "님";
			
			var etc = "";
			for(var i=0,len=Math.min(3, this.playerHistory.length);i<len;i++){
				var etcMember = this.playerHistory[i];
				if(etcMember.url_name != winner.url_name){
					etc += " \#\#_LINK|"+ etcMember.nickname +"|http://yozm.daum.net/"+etcMember.url_name+"_\#\# ";					
				}
			}
			etc += "... 등등을 물리치고 올라온";
			
			message.value = etc + str;
			img_url.value = winner.profile_big_img_url;
			
			form.submit();
		},
		addLoadinfo: function(str){
			if(!daum.Element.visible(this.loadInfo)){
				daum.Element.show(this.loadInfo);				
			}
			this.loadInfo.innerHTML = str;
		},
		finishLoad: function(isContinue){
			this.isIng = false;
			if(!isContinue){
				setTimeout(function(){
					if(!this.isIng){
						daum.Element.hide(this.loadInfo);					
					}
				}.bind(this), 5000);
			}
			daum.Element.removeClassName(this.startBtn, "making");
			daum.Element.hide(this.startBtn);
		},
		loadFail: function(){
			this.addLoadinfo("참가자풀을 만들 수 없어 게임을 할 수 없습니다.<br /><a href=\"http://yozm.daum.net\" target=\"_blank\">요즘</a> 친구를 만들어보세요.");
			this.finishLoad(true);
		}
	}
	new YozmCup();
})();